package ai4games_tests.soccer;

import game2dai.World;
import game2dai.entities.BaseEntity;
import game2dai.fsm.Dispatcher;
import game2dai.fsm.State;
import game2dai.fsm.Telegram;
import game2dai.maths.Vector2D;

public class KeeperPutBallBackInPlay extends State implements Constants {

	private static KeeperPutBallBackInPlay instance = null;

	public static KeeperPutBallBackInPlay state(){
		if(instance == null){
			instance = new KeeperPutBallBackInPlay();
			instance.name = "Put ball into play";
		}
		return instance;
	}


	@Override
	public void enter(BaseEntity owner) {
		GoalKeeper keeper = (GoalKeeper) owner;
		keeper.team.setControllingPlayer(keeper);
		keeper.team.FSM().changeState(TeamDefending.state());
		keeper.team.getOtherTeam().FSM().changeState(TeamDefending.state());
		keeper.team.sendFieldPlayersToRegion();
		keeper.team.getOtherTeam().sendFieldPlayersToRegion();
	}

	@Override
	public void execute(BaseEntity owner, double deltaTime, World world) {
		GoalKeeper keeper = (GoalKeeper) owner;
		Ball ball = keeper.team.pitch.ball;
		Vector2D ballPos = ball.pos();
		Vector2D ballTarget = new Vector2D();
// 
		if(!keeper.isThreatened()){
			PlayerBase receiver = keeper.team.findBestPass(keeper, ballTarget, MaxPassingForce, KeeperMinPassDistance);
			if(receiver != null){
				keeper.team.addNoiseToKick(ballPos, ballTarget);
				Vector2D kickDirection = Vector2D.sub(ballTarget, ballPos);
				keeper.team.pitch.ball.kick(keeper, kickDirection, MaxPassingForce);
				Dispatcher.dispatch(0, keeper.ID(), receiver.ID(), RECEIVE_BALL, ballTarget);
				keeper.FSM().changeState(KeeperTendGoal.state());
				return;
			}
			else {
				// can't find receiver kick ball towards one of the defenders anyway
				// to prevent lockup
			}
		}
		keeper.velocity(Vector2D.ZERO);
	}

	@Override
	public void exit(BaseEntity owner) {
		GoalKeeper keeper = (GoalKeeper) owner;
		keeper.team.pitch.ball.realease();
	}

	@Override
	public boolean onMessage(BaseEntity owner, Telegram tgram) {
		return false;
	}


}
